//
//  ActivityPopupView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/14.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import UIKit
import AVKit
import SnapKit
import JFPopup
import Kingfisher

class ActivityPopupView: UIView {
    
    enum PopupType {
        case image
        case video
    }
    
    // MARK: - Properties
    private var popupType: PopupType = .image
    private var imageUrl: String = ""
    private var videoUrl: String = ""
    private var countdownTimer: Timer?
    private var countdownSeconds: Int = 5
    private var player: AVPlayer?
    private var playerItem: AVPlayerItem?
    private var timeObserver: Any?
    
    // MARK: - UI Components
    private lazy var containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .gray
        view.layer.cornerRadius = 12
        view.layer.masksToBounds = true
        return view
    }()
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
        imageView.addGestureRecognizer(tapGesture)
        return imageView
    }()
    
    private lazy var videoPlayerView: UIView = {
        let view = UIView()
        view.backgroundColor = .black
        view.layer.cornerRadius = 8
        view.layer.masksToBounds = true
        view.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(videoTapped))
        view.addGestureRecognizer(tapGesture)
        return view
    }()
    
    private lazy var playerLayer: AVPlayerLayer = {
        let layer = AVPlayerLayer()
        layer.videoGravity = .resizeAspectFill
        layer.backgroundColor = UIColor.black.cgColor
        return layer
    }()
    
    private lazy var closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "ic_tran_close"), for: .normal)
        button.isUserInteractionEnabled = true
        button.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
        
        // 增加按钮的点击区域
//        button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        
        return button
    }()
    
    private lazy var countdownButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        button.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        button.layer.cornerRadius = 15
        button.layer.masksToBounds = true
        button.layer.borderColor = UIColor.white.cgColor
        button.layer.borderWidth = 1;
        
        // 增加按钮的点击区域
//        button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        
        return button
    }()
    
    // MARK: - Callbacks
    var closeBlock: (() -> Void)?
    var imageTapBlock: (() -> Void)?
    var videoTapBlock: (() -> Void)?
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: - Public Methods
    func configure(type: PopupType, imageUrl: String = "", videoUrl: String = "", second: Int) {
        self.popupType = type
        self.imageUrl = imageUrl
        self.videoUrl = videoUrl
        self.countdownSeconds = second;
        
        switch type {
        case .image:
            setupImageView()
        case .video:
            setupVideoView()
        }
    }
    
    // MARK: - Private Methods
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        addSubview(containerView)
        containerView.addSubview(imageView)
        containerView.addSubview(videoPlayerView)
        containerView.addSubview(closeButton)
        containerView.addSubview(countdownButton)
        
        setupConstraints()
        
        // 添加点击背景关闭功能
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped))
        self.addGestureRecognizer(tapGesture)
    }
    
    private func setupConstraints() {
        containerView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(300)
            make.height.equalTo(400)
        }
        
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        videoPlayerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        closeButton.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.width.height.equalTo(30)
        }
        
        countdownButton.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.width.height.equalTo(30)
        }
        
        // 确保按钮在最上层
        containerView.bringSubviewToFront(closeButton)
        containerView.bringSubviewToFront(countdownButton)
    }
    
    private func setupImageView() {
        imageView.isHidden = false
        videoPlayerView.isHidden = true
        closeButton.isHidden = false
        countdownButton.isHidden = true
        
        xLog("设置图片弹窗，关闭按钮可见")
        
        // 加载图片
        if let url = URL(string: imageUrl) {
            // 这里可以使用图片加载库，暂时使用系统方法
            imageView.kf.setImage(with: url)
        }
    }
    
    private func setupVideoView() {
        imageView.isHidden = true
        videoPlayerView.isHidden = false
        closeButton.isHidden = true
        countdownButton.isHidden = false
        
        xLog("设置视频弹窗，倒计时按钮可见")
        
        // 设置视频播放器
        if let url = URL(string: videoUrl) {
            // 创建 AVPlayerItem
            playerItem = AVPlayerItem(url: url)
            
            // 创建 AVPlayer
            player = AVPlayer(playerItem: playerItem)
            playerLayer.player = player
            
            // 添加到视频视图
            videoPlayerView.layer.addSublayer(playerLayer)
            
            // 监听播放器状态
            playerItem?.addObserver(self, forKeyPath: "status", options: [.new, .initial], context: nil)
            playerItem?.addObserver(self, forKeyPath: "isPlaybackLikelyToKeepUp", options: [.new], context: nil)
            
            // 设置音频会话
            try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
            try? AVAudioSession.sharedInstance().setActive(true)
            
            // 开始播放
            player?.play()
            
            // 监听播放结束，实现循环播放
            NotificationCenter.default.addObserver(self, 
                                               selector: #selector(playerItemDidReachEnd), 
                                               name: .AVPlayerItemDidPlayToEndTime, 
                                               object: playerItem)
            
            // 开始倒计时
            startCountdown()
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "status" {
            if let playerItem = object as? AVPlayerItem {
                switch playerItem.status {
                case .readyToPlay:
                    xLog("视频准备就绪，开始播放")
                    // 确保在主线程更新UI
                    DispatchQueue.main.async {
                        self.updatePlayerLayerFrame()
                    }
                case .failed:
                    xLog("视频播放失败: \(String(describing: playerItem.error))")
                case .unknown:
                    xLog("视频状态未知")
                @unknown default:
                    break
                }
            }
        } else if keyPath == "isPlaybackLikelyToKeepUp" {
            if let playerItem = object as? AVPlayerItem {
                if playerItem.isPlaybackLikelyToKeepUp {
                    xLog("视频播放流畅")
                }
            }
        }
    }
    
    private func updatePlayerLayerFrame() {
        // 确保在正确的时机设置frame
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        playerLayer.frame = videoPlayerView.bounds
        CATransaction.commit()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // 在布局更新时同步更新playerLayer的frame
        if popupType == .video && !videoPlayerView.isHidden {
            updatePlayerLayerFrame()
        }
    }
    
    private func startCountdown() {
        updateCountdownButton()
        
        countdownTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
            self?.countdownSeconds -= 1
            self?.updateCountdownButton()
            
            if self?.countdownSeconds == 0 {
                self?.countdownTimer?.invalidate()
                self?.countdownTimer = nil
                self?.showCloseButton()
            }
        }
    }
    
    private func updateCountdownButton() {
        countdownButton.setTitle("\(countdownSeconds)s", for: .normal)
    }
    
    private func showCloseButton() {
        countdownButton.isHidden = true
        closeButton.isHidden = false
    }
    
    @objc private func playerItemDidReachEnd() {
        guard let player = player else { return }
        player.seek(to: .zero)
        player.play()
    }
    
    @objc private func closeButtonTapped() {
        xLog("关闭按钮被点击")
        stopVideo()
        closeBlock?()
    }
    
    @objc private func backgroundTapped() {
        xLog("背景被点击")
//        stopVideo()
//        closeBlock?()
    }
    
    @objc private func imageTapped() {
        imageTapBlock?()
    }
    
    @objc private func videoTapped() {
        videoTapBlock?()
    }
    
    private func stopVideo() {
        countdownTimer?.invalidate()
        countdownTimer = nil
        
        // 移除观察者
        if let playerItem = playerItem {
            playerItem.removeObserver(self, forKeyPath: "status")
            playerItem.removeObserver(self, forKeyPath: "isPlaybackLikelyToKeepUp")
        }
        
        // 停止播放
        player?.pause()
        player = nil
        playerItem = nil
        
        // 移除通知观察者
        NotificationCenter.default.removeObserver(self)
        
        // 重置音频会话
        try? AVAudioSession.sharedInstance().setActive(false)
    }
    
    deinit {
        stopVideo()
    }
}

// MARK: - Nib Loading
extension ActivityPopupView {
    static func loadFromNib() -> ActivityPopupView {
        return Bundle.main.loadNibNamed("ActivityPopupView", owner: nil, options: nil)?.first as! ActivityPopupView
    }
} 
